console.log("加载到了全局路由守卫")
import router, { loadStaticRoutes } from '@/router/index'
import { useNProgress } from "@/hooks/useNProgress"
import { useAppStoreFn } from '@/store/modules/app'
import { useCache } from "@/hooks/useCache"

import { setPageTitle } from '@/utils';

import { getUrlKey } from "@/utils/split"
import { unCodeAes } from '@/utils/encryption'

const appStore = useAppStoreFn();
const { wsCache } = useCache()

const { start, done } = useNProgress()

const unTokenPage: string[] = ['/login', '/404', '/403'];



// 进入之前
router.beforeEach(async (to, from, next) => {
  start()

  if ((to.path == "/" || to.path == "/home") && getUrlKey("user")) {
    let info = getUrlKey("user");
    if (info) {
      let transToken = unCodeAes(info);
      console.log("perm", transToken)
      if (transToken) {
        wsCache.set(appStore.token, transToken);
      }
    }
  }

  setPageTitle(to.meta.title);

  const token = wsCache.get(appStore.getToken)

  if (token) { // 有token
    if (appStore.isAddRouters) {
      next()
      return
    }
    await appStore.generateRoutes()
    // 生成动态菜单
    // 加载静态路由
    loadStaticRoutes()
    next()
  } else {
    let toPage = to.path;
    if (unTokenPage.includes(toPage)) {
      next()
    } else {
      window.location.href = import.meta.env.VITE_APP_CLOUD_URL;
    }
  }
})

router.afterEach((to, from) => {
  done()
})